#!/usr/bin/python3

import requests
import os
import argparse


def main():
    parser = argparse.ArgumentParser(
        description="mkchkupdate")
    parser.add_argument("-t", "--total", type=int,
                        default=5, help="total lint")
    parser.add_argument('packages', metavar='N', type=str, nargs='+',
                        help='packages')
    args = parser.parse_args()
    packages = args.packages
    total = args.total
    for i in packages:
        print("{}:".format(i))
        r = requests.get(
            "https://release-monitoring.org/api/projects/?pattern={}".format(i))
        d = r.json()
        print("Anitya:")
        index = 1
        if d["total"] != 0:
            for j in d["projects"]:
                if index <= total:
                    print("Name: {}, Lastest Version: {}, CHKUPDATE: anitya::id={}, Homepage: {}".format(
                        j["name"], j["stable_versions"][0] if len(j["stable_versions"]) != 0 else "None", j["id"], j["homepage"] if j["homepage"] else "None"))
                    index += 1
                else:
                    break
        srcs = []
        print("Github:")
        package_path = search_package_path(i)
        if package_path:
            with open("{}/spec".format(package_path)) as f:
                spec = f.readlines()
                for j in spec:
                    if "SRCS=" in j:
                        if len(j.split("::")) > 1:
                            srcs += j.split("::")[1][:-1].split('\n')
                        else:
                            srcs += j[:-1].split('\n')
            for k in srcs:
                if "github" in k:
                    split_k = k.split("/")
                    print(
                        "CHKUPDATE: github::repo={}/{}".format(split_k[3], split_k[4]))


def search_package_path(package_name: str) -> str:
    with os.scandir(".") as dir1:
        for section in dir1:
            if section.is_dir() and not section.name.startswith('.'):
                with os.scandir(section) as dir2:
                    for package in dir2:
                        if package.name == package_name and package.is_dir() and os.path.isdir(
                                os.path.join(package, "autobuild")):
                            return package.path[2:]
                        # search subpackage, like arch-install-scripts/01-genfstab
                        path = package
                        if os.path.isdir(path) and section.name != "groups":
                            with os.scandir(path) as dir3:
                                for subpackage in dir3:
                                    if subpackage.name != "autobuild" and subpackage.is_dir():
                                        try:
                                            with open(os.path.join(subpackage, "defines"), "r") as f:
                                                defines = f.readlines()
                                        except:
                                            with open(os.path.join(subpackage, "autobuild/defines"), "r") as f:
                                                defines = f.readlines()
                                        finally:
                                            for line in defines:
                                                if "PKGNAME=" in line and package_name in line:
                                                    return package.path[2:]


if __name__ == "__main__":
    main()
